<template>
  <div @click="uploadHandle" class="image-card">
    <i v-show="tempFilePath && closeable" @click="clear" class="iconfont icon-close"></i>
    <i v-show="!tempFilePath" class="iconfont icon-jiahao"></i>
    <img class="image-card__image" v-show="tempFilePath" :src="tempFilePath || url" alt="" />
  </div>
</template>

<script>
import { ref } from 'vue';
import { upload, chooseImage } from '@/utils/upload';
import './index.less';

export default {
  emits: ['change'],
  props: {
    closeable: Boolean,
    url: String,
  },
  setup(props, { emit }) {
    const uploadUrl = 'https://api.aunt.geekbuluo.com/upload/file';
    const tempFilePath = ref(props.url);

    const uploadHandle = () => {
      chooseImage().then((res) => {
        [tempFilePath.value] = res.tempFilePaths;
        upload(tempFilePath.value).then((res) => emit('change', res));
      });
    };

    const clear = (e) => {
      tempFilePath.value = '';
      emit('change', '');
      e.stopPropagation();
    };
    return {
      uploadHandle,
      clear,
      uploadUrl,
      tempFilePath,
    };
  },
};
</script>
